package com.nh.glory.ware.service.system;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.exceptions.ApiException;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nh.glory.core.constant.Constants;
import com.nh.glory.core.util.DigestUtil;
import com.nh.glory.core.util.Func;
import com.nh.glory.data.mapper.UserMapper;
import com.nh.glory.data.model.User;
import com.nh.glory.data.vo.UserInfo;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 服务实现类
 */
@Service
@AllArgsConstructor
public class UserService extends ServiceImpl<UserMapper, User> {

    private final BCryptPasswordEncoder encoder;

    public boolean submit(User user) {
        if (Func.isNotEmpty(user.getPassword())) {
            user.setPassword(encoder.encode(user.getPassword()));
        }
        Integer cnt = baseMapper.selectCount(Wrappers.<User>query().lambda().eq(User::getAccount, user.getAccount()));
        if (cnt > 0) {
            throw new ApiException("当前用户已存在!");
        }
        return saveOrUpdate(user);
    }

    public IPage<User> selectUserPage(IPage<User> page, User user) {
        return page.setRecords(baseMapper.selectUserPage(page, user));
    }

    public UserInfo userInfo(String account, String password) {
        UserInfo userInfo = new UserInfo();
        User user = baseMapper.getUser(account, password);
        userInfo.setUser(user);
        if (Func.isNotEmpty(user)) {
            List<String> roleAlias = baseMapper.getRoleAlias(Func.toStrArray(user.getRoleId().toString()));
            userInfo.setRoles(roleAlias);
        }
        return userInfo;
    }

    public boolean grant(String userIds, String roleIds) {
        User user = new User();
        user.setRoleId(Func.toLong(roleIds));
        return this.update(user, Wrappers.<User>update().lambda().in(User::getId, Func.toIntList(userIds)));
    }

    public boolean resetPassword(String userIds) {
        User user = new User();
        user.setPassword(encoder.encode(Constants.DEFAULT_PASSWORD));
        return this.update(user, Wrappers.<User>update().lambda().in(User::getId, Func.toLongList(userIds)));
    }

    public List<String> getRoleName(String roleIds) {
        return baseMapper.getRoleName(Func.toStrArray(roleIds));
    }

    public List<String> getDeptName(String deptIds) {
        return baseMapper.getDeptName(Func.toStrArray(deptIds));
    }

}
